/*
 * Licensed under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.submarine.registry.zookeeper;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.submarine.common.Constants;
import org.submarine.common.Logger;
import org.submarine.common.URL;
import org.submarine.config.ConfigUtil;
import org.submarine.registry.AbstractRegistry;
import org.submarine.registry.listener.NotifyListener;
import org.submarine.util.CalendarUtil;

/**
 * @file org.submarine.registry.zookeeper.ZookeeperRegistry.java
 *
 * Zookeeper注册
 * 
 * @author gaojian
 * @created 2013-8-17 下午11:36:31
 * @version 0.0.1
 * @since 0.0.1
 * 
 */
public class ZookeeperRegistry extends AbstractRegistry {
	
	private static final Logger logger = Logger.getLogger(ZookeeperRegistry.class);
	
    private final ConcurrentMap<URL, HashSet<NotifyListener>> zkListeners = new ConcurrentHashMap<URL, HashSet<NotifyListener>>();
	
	private ZkClient zkClient = null;
	
	public ZookeeperRegistry() {
		String address = ConfigUtil.getProperty(Constants.REGISTRY_ADDRESS_KEY);
		String applicationName = ConfigUtil.getProperty(Constants.APPLICATION_NAME_KEY);
		String zookeeperServer = address.substring(12, address.length() - 5);
	
		try {
			zkClient = new ZkClient(zookeeperServer, Constants.CONNECTIONT_IMEOUT);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("连接Zookeeper服务器超时，时间" + Constants.CONNECTIONT_IMEOUT + "毫秒。", e.getCause());
			throw new RuntimeException("连接Zookeeper服务器超时，时间" + Constants.CONNECTIONT_IMEOUT + "毫秒。", e.getCause());
		}
		System.out.println(CalendarUtil.timestampFormat(new Date()) + applicationName + " connected to zookeeper server("+ zookeeperServer +")!");
		create(Constants.ROOT_PATH, true);
		create(Constants.ROOT_AGENT_PATH, true);
		create(Constants.ROOT_COLLECTOR_PATH, true);
	}
	
	/**
	 * 
	 * 创建path
	 *
	 * @author gaojian
	 * @created 2013-8-18 上午2:17:24
	 *
	 * @param path
	 * @param persistent
	 */
	private void create(String path, boolean persistent) {
		if (persistent) {
			if (!zkClient.exists(path)) {
				zkClient.createPersistent(path);
			}
		} else {
			zkClient.createEphemeral(path);
		}
	}
	
	/**
	 * 
	 * 根据url构建path
	 *
	 * @author gaojian
	 * @created 2013-8-18 上午2:17:44
	 *
	 * @param url
	 * @return
	 */
	private String buildPath(URL url) {
		return Constants.ROOT_PATH + Constants.FILE_SEPARATOR + url.getSide() + Constants.FILE_SEPARATOR + url.getHost() + Constants.ENGLISH_COLON + url.getPort();
	}

	/* (non-Javadoc)
	 * @see org.submarine.registry.FailbackRegistry#doRegister(org.submarine.common.URL)
	 */
	@Override
	protected void doRegister(URL url) {
		create(buildPath(url), false);
	}

	/* (non-Javadoc)
	 * @see org.submarine.registry.FailbackRegistry#doUnregister(org.submarine.common.URL)
	 */
	@Override
	protected void doUnregister(URL url) {
		zkClient.delete(buildPath(url));
	}

	/* (non-Javadoc)
	 * @see org.submarine.registry.FailbackRegistry#doSubscribe(org.submarine.common.URL, org.submarine.registry.listener.NotifyListener)
	 */
	@Override
	protected void doSubscribe(final URL consumerURL, final NotifyListener listener) {
		Set<URL> urls = new HashSet<URL>();
		
        Set<NotifyListener> listeners = zkListeners.get(consumerURL);
        if (listeners == null) {
            zkListeners.putIfAbsent(consumerURL, new HashSet<NotifyListener>());
            listeners = zkListeners.get(consumerURL);
        }
        List<String> children = zkClient.subscribeChildChanges(Constants.ROOT_COLLECTOR_PATH, new IZkChildListener() {
			@Override
			public void handleChildChange(String parentPath, List<String> currentChildren) throws Exception {
				ZookeeperRegistry.this.notify(consumerURL, listener, toUrls(parentPath, currentChildren));
			}
		});
        if (children != null) {
        	urls.addAll(toUrls(Constants.ROOT_COLLECTOR_PATH, children));
        }
        notify(consumerURL, listener, urls);
	}
	
	private Set<URL> toUrls(String parent, List<String> providers) {
		Set<URL> urls = new HashSet<URL>();
		if (providers != null && providers.size() > 0) {
            for (String provider : providers) {
            	urls.add(URL.valueOf(parent + Constants.FILE_SEPARATOR + provider));
            }
        }
        return urls;
    }
	
	/* (non-Javadoc)
	 * @see org.submarine.registry.FailbackRegistry#doUnsubscribe(org.submarine.common.URL, org.submarine.registry.listener.NotifyListener)
	 */
	@Override
	protected void doUnsubscribe(URL url, NotifyListener listener) {
		// TODO Auto-generated method stub
		
	}
	
	public Set<URL> getInitCollectorURL() {
		List<String> list = zkClient.getChildren(Constants.ROOT_COLLECTOR_PATH);
		return toUrls(Constants.ROOT_COLLECTOR_PATH, list);
	}

}
